package cn.ekuma.epos.customerfinishing;

import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JToolBar;
import cn.ekuma.data.ui.swing.AbstractDAOJEditor;
import cn.ekuma.data.ui.swing.JChildDAOEditorPanel;
import cn.ekuma.epos.crm.CustomerAddressEditor;
import cn.ekuma.epos.crm.CustomerContactEditor;
import cn.ekuma.epos.crm.CustomerPeopleEditor;
import cn.ekuma.epos.crm.CustomerStoreValueCardEditor;
import cn.ekuma.epos.crm.contract.ContractEditor;
import cn.ekuma.epos.crm.contract.JContractProductEditor;
import cn.ekuma.epos.crm.contract.model.ContractProductTableModel;
import cn.ekuma.epos.crm.contract.model.ContractTableModel;
import cn.ekuma.epos.crm.link.JCustomerActionLinkPanel;
import cn.ekuma.epos.crm.link.JCustomerOrderLinkPanel;
import cn.ekuma.epos.crm.link.JCustomerScoreDiaryLinkPanel;
import cn.ekuma.epos.crm.link.JCustomerShardOrderLinkPanel;
import cn.ekuma.epos.crm.model.CustomerAddressTableModel;
import cn.ekuma.epos.crm.model.CustomerContactTableModel;
import cn.ekuma.epos.crm.model.CustomerPeopleTableModel;
import cn.ekuma.epos.crm.model.CustomerStoreValueCardTableModel;
import cn.ekuma.epos.crm.service.TelephoneEditor;
import cn.ekuma.epos.crm.service.model.TelephoneTableModel;
import cn.ekuma.epos.customerfinishing.model.CustomerTableModel;
import cn.ekuma.epos.datalogic.I_DataLogicERP;
import cn.ekuma.epos.datalogic.I_DataLogicSystem;
import cn.ekuma.epos.db.table.I_Customer;
import cn.ekuma.epos.module.ERP_UI_Swing_Model;
import cn.ekuma.epos.panel.AbstractJModelFinishingPanel;

import com.openbravo.bean.AppUser;
import com.openbravo.bean.BusinessPartner;
import com.openbravo.bean.CustomerCategory;
import com.openbravo.bean.crm.concerns.Concerns;
import com.openbravo.bean.erp.OperationCustomerCategory;
import com.openbravo.data.basic.BasicException;
import com.openbravo.data.gui.MessageInf;
import com.openbravo.data.loader.query.QBF;
import com.openbravo.data.loader.query.QBFCompareEnum;
import com.openbravo.data.loader.query.QBFParameter;
import com.openbravo.data.loader.query.QBFParameters;
import com.openbravo.data.loader.ui.JQBFParametersPanel;
import com.openbravo.data.user.DirtyManager;
import com.openbravo.format.Formats;

import com.openbravo.pos.base.AppLocal;
import com.openbravo.pos.base.AppView;
import com.openbravo.pos.base.BeanFactoryException;
import com.openbravo.pos.customers.CustomersEditor;
import com.openbravo.pos.panels.JDropCustomerByCategoryPanel;
import com.openbravo.pos.panels.JDropCustomerByConcernsPanel;
import com.openbravo.pos.panels.JDropCustomerByOperationCategoryPanel;
import com.openbravo.pos.panels.event.CustomerCategoryChangedListener;
import com.openbravo.pos.panels.event.TimeCycleChangedEvent;
import com.openbravo.pos.panels.navigator.JConcernsNavigator;
import com.openbravo.pos.panels.navigator.JCustomerCategoryNavigator;
import com.openbravo.pos.panels.navigator.JOperationCustomerCategoryNavigator;
import com.openbravo.pos.panels.navigator.event.ConcernsChangedListener;
import com.openbravo.pos.panels.navigator.event.OperationCustomerCategoryChangedListener;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;

public class JCustomerFinishingPanel extends AbstractJModelFinishingPanel<BusinessPartner,BusinessPartner> {
	/**
	 * 
	 */
	private static final long serialVersionUID = 8842624968131384340L;

	private JCustomerCategoryNavigator customerCategoryNavigator;
	private JOperationCustomerCategoryNavigator operationCustomerCategoryNavigator;

	private JConcernsNavigator concernsNavigator;

	private AppUser user;
	
	/**
	 * Create the panel.
	 */
	public JCustomerFinishingPanel() {
		super(new CustomerTableModel());
	}


	protected void m_jBarcode1ActionPerformed(ActionEvent e) {
		String sCode = inputCode.getText();
		if (sCode.isEmpty()) {
			return;
		}
		QBFParameters paras=new QBFParameters();
		paras.or(new QBFParameter(I_Customer.CARD).equal(sCode))
		     .or(new QBFParameter(I_Customer.CITY).equal(sCode))
		     .or(new QBFParameter(I_Customer.POSTAL).equal(sCode))
		     .or(new QBFParameter(I_Customer.NAME1).like(sCode))
		     .or(new QBFParameter(I_Customer.COUNTRY).equal(sCode))
		     .or(new QBFParameter(I_Customer.CITY).equal(sCode))
		     .or(new QBFParameter(I_Customer.SEARCHKEY).like(sCode))
		     .or(new QBFParameter(I_Customer.REGION).equal(sCode)) 
		     .or(new QBFParameter(I_Customer.FAX).equal(sCode)) 
		     .or(new QBFParameter(I_Customer.PHONE).equal(sCode))
		     .or(new QBFParameter(I_Customer.PHONE2).equal(sCode))
		     .or(new QBFParameter(I_Customer.ADDRESS).equal(sCode)) ;
		     
		try {
			tableModel.resert(mode.getDLERP().query(BusinessPartner.class, paras));
		} catch (BasicException e1) {
			new MessageInf(e1).show(this);
		}     
	}


	String[] fields=new String[]{I_Customer.CREATEDATE, I_Customer.CREATEDATE, I_Customer.CATEGORY};
	public void reQuery() {

		QBF qbf=QBF.c();
		for(int i=0;i<beforeFilterParas.length;i=i+2)
			if(beforeFilterParas[i]!=QBFCompareEnum.COMP_NONE)
				qbf.and(new QBFParameter(fields[i/2],(QBFCompareEnum) beforeFilterParas[i],beforeFilterParas[i+1]));
		try {
			tableModel.resert(mode.getDLERP().query(BusinessPartner.class, qbf.build()));
			if (beforeFilterParas[1] != null)
				jTxtStartDate.setText(Formats.TIMESTAMP
						.formatValue(beforeFilterParas[1]));
			else
				jTxtStartDate.setText(null);
			if (beforeFilterParas[3] != null)
				jTxtEndDate.setText(Formats.TIMESTAMP
						.formatValue(beforeFilterParas[3]));
			else
				jTxtEndDate.setText(null);
		} catch (BasicException ex) {
			new MessageInf(ex).show(this);
		}
	}

	@Override
	public Object createValue() throws BasicException {
		Object[] afilter = new Object[6];

		// Date range
		Object startdate = Formats.TIMESTAMP
				.parseValue(jTxtStartDate.getText());
		Object enddate = Formats.TIMESTAMP.parseValue(jTxtEndDate.getText());

		afilter[0] = (startdate == null) ? QBFCompareEnum.COMP_NONE
				: QBFCompareEnum.COMP_GREATEROREQUALS;
		afilter[1] = startdate;
		afilter[2] = (enddate == null) ? QBFCompareEnum.COMP_NONE
				: QBFCompareEnum.COMP_LESS;
		afilter[3] = enddate;

		//category
		afilter[4] = QBFCompareEnum.COMP_NONE;
		afilter[5] = null;
		
		return afilter;
	}

	@Override
	public String getTitle() {
		return null;//AppLocal.getIntString("Menu.ProdcutFinishing");
	}

	@Override
	public void activate() throws BasicException {
        customerCategoryNavigator.loadData();
        operationCustomerCategoryNavigator.loadData();
	}

	@Override
	public boolean deactivate() {
		return true;
	}

	@Override
	public JComponent getComponent() {
		return this;
	}

	@Override
	public Object getBean() {
		return this;
	}

	
	
	@Override
	public void initFinishPanel(AppView app) throws BeanFactoryException {
		user=(AppUser) app.getAppUserView().getUser();
		
        JChildDAOEditorPanel customerPeoplePanel=new  JChildDAOEditorPanel(mode.getDLERP(),new CustomerPeopleTableModel(),new CustomerPeopleEditor(new DirtyManager()));
		linkTabPanel.add(customerPeoplePanel.getTabName(), customerPeoplePanel);
        addParentNodeChangeListener(customerPeoplePanel);
        
        JChildDAOEditorPanel customerAddressPanel=new  JChildDAOEditorPanel(mode.getDLERP(),new CustomerAddressTableModel(),new CustomerAddressEditor(new DirtyManager()));
		linkTabPanel.add(customerAddressPanel.getTabName(), customerAddressPanel);
        addParentNodeChangeListener(customerAddressPanel);
        
        JChildDAOEditorPanel customerContactPanel=new  JChildDAOEditorPanel(mode.getDLERP(),new CustomerContactTableModel(),new CustomerContactEditor(new DirtyManager()));
		linkTabPanel.add(customerContactPanel.getTabName(), customerContactPanel);
        addParentNodeChangeListener(customerContactPanel);
        
        JChildDAOEditorPanel customerStoreValueCardPanel=new  JChildDAOEditorPanel(mode.getDLERP(),new CustomerStoreValueCardTableModel(),new CustomerStoreValueCardEditor(new DirtyManager()));
		linkTabPanel.add(customerStoreValueCardPanel.getTabName(), customerStoreValueCardPanel);
        addParentNodeChangeListener(customerStoreValueCardPanel);
        
        JChildDAOEditorPanel customerTelephonePanel=new  JChildDAOEditorPanel(mode.getDLERP(),new TelephoneTableModel(),new TelephoneEditor(new DirtyManager(), user, dlSystem, mode.getDLERP()));
		linkTabPanel.add(customerTelephonePanel.getTabName(), customerTelephonePanel);
        addParentNodeChangeListener(customerTelephonePanel);
        
        JChildDAOEditorPanel contractEditorPanel=new  JChildDAOEditorPanel(mode.getDLERP(),new ContractTableModel(),new ContractEditor(new DirtyManager(), user, dlSystem,  mode.getDLERP()));
		linkTabPanel.add(contractEditorPanel.getTabName(), contractEditorPanel);
        addParentNodeChangeListener(contractEditorPanel);
        
        JChildDAOEditorPanel contractProductEditorPanel=new  JChildDAOEditorPanel(mode.getDLERP(),new ContractProductTableModel(),new JContractProductEditor(mode.getDLERP(),new DirtyManager() ));
        linkTabPanel.add(contractProductEditorPanel.getTabName(), contractProductEditorPanel);
        addParentNodeChangeListener(contractProductEditorPanel);
        
        linkTabPanel.add(JCustomerShardOrderLinkPanel.getTabName(),new  JCustomerShardOrderLinkPanel(app,mode.getDLERP(),mode.getDLReceipts()));
        linkTabPanel.add(JCustomerOrderLinkPanel.getTabName(),new  JCustomerOrderLinkPanel(app,mode.getDLERP()));
        linkTabPanel.add(JDropCustomerByCategoryPanel.getTabName(),new JDropCustomerByCategoryPanel(mode.getDLERP()));
        linkTabPanel.add(JDropCustomerByOperationCategoryPanel.getTabName(),new JDropCustomerByOperationCategoryPanel(mode.getDLERP()));
        linkTabPanel.add(JCustomerScoreDiaryLinkPanel.getTabName(),new JCustomerScoreDiaryLinkPanel(mode.getDLERP())); 
        linkTabPanel.add(JDropCustomerByConcernsPanel.getTabName(),new JDropCustomerByConcernsPanel(mode.getDLERP()));
        
        
        linkTabPanel.add(JCustomerActionLinkPanel.getTabName(),new JCustomerActionLinkPanel(mode.getDLERP()));
        
	}

	@Override
	public void timeCycleChanged(TimeCycleChangedEvent e) {
		if (beforeFilterParas == null)
			try {
				beforeFilterParas = (Object[]) createValue();
			} catch (BasicException ex) {
				new MessageInf(ex).show(this);
				return;
			}
			
			// Date range
			Object startdate = e.getStartDate();
			Object enddate =e.getEndDate();

			beforeFilterParas[0] = (startdate == null) ? QBFCompareEnum.COMP_NONE
					: QBFCompareEnum.COMP_GREATEROREQUALS;
			beforeFilterParas[1] = startdate;
			beforeFilterParas[2] = (enddate == null) ? QBFCompareEnum.COMP_NONE
					: QBFCompareEnum.COMP_LESS;
			beforeFilterParas[3] = enddate;
			reQuery();
	}

	@Override
	protected void configNavigator(JPanel jNavigatorToolBar, final JPanel jNavigator) {
		customerCategoryNavigator = new JCustomerCategoryNavigator(mode.getDLERP());
		customerCategoryNavigator.addCustomerCategoryChangedListener(new CustomerCategoryChangedListener(){

			@Override
			public void valueSelectChanged(CustomerCategory obj) {
				if (beforeFilterParas == null)
					try {
						beforeFilterParas = (Object[]) createValue();
					} catch (BasicException e) {
						new MessageInf(e).show(JCustomerFinishingPanel.this);
						return;
					}
					// Categoria
					beforeFilterParas[4] = QBFCompareEnum.COMP_EQUALS;
					beforeFilterParas[5] = obj.getID();
					reQuery();
			}
			
		});
		jNavigator.add(customerCategoryNavigator, "category");

		operationCustomerCategoryNavigator = new JOperationCustomerCategoryNavigator(
				mode.getDLERP());
		operationCustomerCategoryNavigator.addOperationCustomerCategoryChangedListener
				(new OperationCustomerCategoryChangedListener(){

					@Override
					public void valueSelectChanged(OperationCustomerCategory obj) {
						try {
							tableModel.resert(mode.getDLERP().listCustomerByOperationCategory(obj.getID()));
						} catch (BasicException e) {
							new MessageInf(e).show(JCustomerFinishingPanel.this);
						}
						
					}
					
				});
		jNavigator.add(operationCustomerCategoryNavigator, "operationCategory");
		
		concernsNavigator = new JConcernsNavigator(
				mode.getDLERP());
		concernsNavigator.addConcernsChangedListener(new ConcernsChangedListener(){

					@Override
					public void valueSelectChanged(Concerns obj) {
					}
					
				});
		jNavigator.add(concernsNavigator, "customerConcerns");
		
		JButton button_2 = new JButton(AppLocal.getIntString("Menu.CustomerCategories"));
		button_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				cl1.show(jNavigator, "category");
			}
		});
		jNavigatorToolBar.add(button_2);

		JButton btnNewButton = new JButton(
				AppLocal.getIntString("label.operationCustomerCategory"));
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				cl1.show(jNavigator, "operationCategory");
			}
		});
		jNavigatorToolBar.add(btnNewButton);
		
		JButton btnNewButton1 = new JButton(
				AppLocal.getIntString("label.customerConcerns"));
		btnNewButton1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				cl1.show(jNavigator, "customerConcerns");
			}
		});
		jNavigatorToolBar.add(btnNewButton1);
		
		
		JPanel panel_3 = new JPanel();
		jNavigator.add(panel_3, "QBFPanel");
		panel_3.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_2 = new JPanel();
		panel_2.setPreferredSize(new Dimension(10, 155));
		panel_3.add(panel_2, BorderLayout.NORTH);
		GridBagLayout gbl_panel_2 = new GridBagLayout();
		gbl_panel_2.columnWidths = new int[]{120, 120, 0};
		gbl_panel_2.rowHeights = new int[]{31, 31, 31, 0};
		gbl_panel_2.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
		gbl_panel_2.rowWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE};
		panel_2.setLayout(gbl_panel_2);
		
		JButton button_1 = new JButton(AppLocal.getIntString("label.birthday"));
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
			}
		});
		GridBagConstraints gbc_button_1 = new GridBagConstraints();
		gbc_button_1.fill = GridBagConstraints.BOTH;
		gbc_button_1.insets = new Insets(0, 0, 5, 5);
		gbc_button_1.gridx = 0;
		gbc_button_1.gridy = 0;
		panel_2.add(button_1, gbc_button_1);
		
		JButton button_8 = new JButton("不可见");
		button_8.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
			}
		});
		GridBagConstraints gbc_button_8 = new GridBagConstraints();
		gbc_button_8.fill = GridBagConstraints.BOTH;
		gbc_button_8.insets = new Insets(0, 0, 5, 0);
		gbc_button_8.gridx = 1;
		gbc_button_8.gridy = 0;
		panel_2.add(button_8, gbc_button_8);
		
		JButton btnNewButton_1 = new JButton("积分对换");
		GridBagConstraints gbc_btnNewButton_1 = new GridBagConstraints();
		gbc_btnNewButton_1.insets = new Insets(0, 0, 5, 5);
		gbc_btnNewButton_1.gridx = 0;
		gbc_btnNewButton_1.gridy = 1;
		panel_2.add(btnNewButton_1, gbc_btnNewButton_1);
		
		JButton btnNewButton_2 = new JButton("积分调整");
		GridBagConstraints gbc_btnNewButton_2 = new GridBagConstraints();
		gbc_btnNewButton_2.insets = new Insets(0, 0, 5, 0);
		gbc_btnNewButton_2.gridx = 1;
		gbc_btnNewButton_2.gridy = 1;
		panel_2.add(btnNewButton_2, gbc_btnNewButton_2);
		
		JQBFParametersPanel qbfPanel=new JQBFParametersPanel(){

			@Override
			public void doQBFParametersFilter(QBFParameters paras) {
				try {
					tableModel.resert(mode.getDLERP().query(BusinessPartner.class, paras));
				} catch (BasicException e) {
					new MessageInf(e).show(this);
				}
			}
        };
        qbfPanel.setShowFieldCount(6);
        qbfPanel.setFields(CustomerTableModel.getQBFFields());
        panel_3.add(qbfPanel, BorderLayout.CENTER);
	}

	@Override
	protected void configToolBar(JToolBar jToolBar12) {
	}

	@Override
	protected AbstractDAOJEditor<BusinessPartner> getEditor() {
		return  new CustomersEditor(mode.getDLERP(), new DirtyManager());
	}


	@Override
	protected BusinessPartner convectToViewModel(BusinessPartner obj) {
		return obj;
	}


	@Override
	protected BusinessPartner convectToEditModel(BusinessPartner obj) throws BasicException {
		return obj;
	}


	@Override
	public String getModelName() {
		return ERP_UI_Swing_Model.MODEL_NAME;
	}

}
